package com.duojuhe.coremodule.sms.service.impl;

import com.duojuhe.cache.SmsRepeatSendCache;
import com.duojuhe.common.constant.SystemConstants;
import com.duojuhe.coremodule.sms.enums.SmsEnum;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.Result;
import com.duojuhe.common.utils.idgenerator.UUIDUtils;
import com.duojuhe.coremodule.sms.pojo.record.SmsSendDto;
import com.duojuhe.coremodule.sms.utils.SMSUtil;
import com.duojuhe.coremodule.BaseService;
import com.duojuhe.coremodule.sms.entity.SmsRecord;
import com.duojuhe.coremodule.sms.entity.SmsSendTaskDetail;
import com.duojuhe.coremodule.sms.mapper.SmsRecordMapper;
import com.duojuhe.coremodule.sms.mapper.SmsSendTaskDetailMapper;
import com.duojuhe.coremodule.sms.pojo.record.SmsRepeatRecordDto;
import com.duojuhe.coremodule.sms.service.HandlerSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class HandlerSmsServiceImpl extends BaseService implements HandlerSmsService {
    @Resource
    private SmsRepeatSendCache smsRepeatSendCache;
    @Resource
    private SmsSendTaskDetailMapper smsSendTaskDetailMapper;
    @Resource
    private SmsRecordMapper smsRecordMapper;

    @Override
    public void handlerSendSms(SmsRepeatRecordDto smsRepeatRecordDto) {
        smsUtilSendMessage(smsRepeatRecordDto);
    }



    /**
     * 阿里云短信发送
     * @param repeatRecordDto
     */
    private void smsUtilSendMessage(SmsRepeatRecordDto repeatRecordDto) {
        //当前时间
        Date nowDate = new Date();
        //手机号码
        String mobileNumber = repeatRecordDto.getMobileNumber();
        //发送ip
        String smsSendIp = repeatRecordDto.getSmsSendIp();
        //短信发送任务明细id
        String sendTaskDetailId = repeatRecordDto.getSendTaskDetailId();
        //短信发送服务商id
        String ispId = repeatRecordDto.getIspId();
        //短信发送渠道id
        String channelId = repeatRecordDto.getChannelId();
        //调用阿里云短信接口
        log.info("【短信发送】第"+repeatRecordDto.getSendNumber()+"次，发送对象详情{}" ,repeatRecordDto.toString());
        Result result = sendSmsMessage(new SmsSendDto(repeatRecordDto));
        //短信发送状态
        String sendStatusCode = SmsEnum.SmsSendStatus.SMS_SEND_SUCCESS.getKey();
        if (!result.isSuccess()) {
            // 发送短信失败，新增一条短信发送失败记录
            sendStatusCode = SmsEnum.SmsSendStatus.SMS_SEND_FAIL.getKey();
        }
        //发送次数
        if (StringUtils.isNotBlank(sendTaskDetailId)){
            //任务明细
            SmsSendTaskDetail taskDetail = new SmsSendTaskDetail();
            taskDetail.setDetailId(sendTaskDetailId);
            taskDetail.setSendStatusCode(sendStatusCode);
            taskDetail.setSendTime(nowDate);
            taskDetail.setRemark(result.getData().toString());
            smsSendTaskDetailMapper.updateByPrimaryKeySelective(taskDetail);
        }
        //发送次数
        int sendNumber = repeatRecordDto.getSendNumber()+1;
        //判断是否需要重发
        if (ErrorCodes.SMS_REQUEST_ERROR.getCode()==result.getErrorCode().getCode()&& SystemConstants.SMS_SEND_FAIL_REPEAT_NUMBER>sendNumber){
            repeatRecordDto.setSendNumber(sendNumber);
            smsRepeatSendCache.putSmsRecordCache(repeatRecordDto);
        }else {
            //插入短信发送记录
            SmsRecord smsRecord = new SmsRecord();
            smsRecord.setRecordId(UUIDUtils.getUUID32());
            smsRecord.setContent(repeatRecordDto.getTemplateContent());
            smsRecord.setMobileNumber(mobileNumber);
            smsRecord.setCreateTime(nowDate);
            smsRecord.setSendStatusCode(sendStatusCode);
            smsRecord.setRemark(result.getData().toString());
            smsRecord.setSendIp(smsSendIp);
            smsRecord.setCreateDeptId(repeatRecordDto.getCreateDeptId());
            smsRecord.setCreateUserId(repeatRecordDto.getCreateUserId());
            smsRecord.setTenantId(repeatRecordDto.getTenantId());
            smsRecord.setSendTaskId(repeatRecordDto.getSendTaskId());
            smsRecord.setSendTaskDetailId(repeatRecordDto.getSendTaskDetailId());
            smsRecord.setSendNumber(sendNumber);
            smsRecord.setChannelId(channelId);
            smsRecord.setIspId(ispId);
            log.info("【短信发送任务】发送记录{}" ,smsRecord.toString());
            smsRecordMapper.insertSelective(smsRecord);
        }
    }

    /**
     * 短信发送
     * @param smsSendDto
     * @return
     */
    private Result sendSmsMessage(SmsSendDto smsSendDto) {
        //模板编码
        String templateCode = smsSendDto.getTemplateCode();
        //短信签名
        String smsSign = smsSendDto.getSignName();
        //扩展参数
        String templateParam = smsSendDto.getTemplateParam();
        //接口账号
        String account = smsSendDto.getChannelAccount();
        //接口密码
        String password = smsSendDto.getChannelPassword();
        //手机号码
        String mobile = smsSendDto.getMobileNumber();
        //发送ip
        String sendIp = smsSendDto.getSmsSendIp();
        //短信发送服务商code
        String ispCode = smsSendDto.getIspCode();
        //短信内容
        String content = smsSendDto.getTemplateContent();
        if (StringUtils.isBlank(SmsEnum.SmsIsp.getValueByKey(ispCode))){
            return Result.fail("短信ispCode错误!");
        }
        if (SmsEnum.SmsIsp.aliyun.getKey().equals(ispCode)){
            return SMSUtil.aliYunSendSms(mobile,templateCode, templateParam, account, password, smsSign,sendIp);
        }else{
            return SMSUtil.huaXinSendSms(mobile,content,account, password, sendIp);
        }
    }
}
